//
//  WithdrawViewController.m
//  YTwallet
//
//  Created by ZhangLin on 2019/3/26.
//  Copyright © 2019年 hadrlog. All rights reserved.
//

#import "WithdrawViewController.h"
#import "WithdrawView.h"
#import "HNineCollectionViewCell.h"
#import "UITextField+ExtentRange.h"

#import "GetReceiptCardModelPack.h"


#define WIDTH  [[UIScreen mainScreen]bounds].size.width

#define HEIGHT [[UIScreen mainScreen]bounds].size.height

@interface WithdrawViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITextFieldDelegate>
@property(nonatomic,strong)NSMutableArray *titleArray;
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)WithdrawView *wv;
@property(nonatomic,strong)UIButton *delBtn;
@property(nonatomic,strong)UIButton *payBtn;
@property(nonatomic,strong)UIButton *zeroBtn;
@property(nonatomic,strong)NSString* HoriginalAmount;
@property(nonatomic,strong)NSString *HnewAccount;

@end

@implementation WithdrawViewController

-(NSMutableArray *)titleArray
{
    if (_titleArray == nil) {
        _titleArray = [NSMutableArray array];
    }
    return _titleArray;
}

#pragma mark 初始化
-(void)loadView{
    [super loadView];
    self.wv = [[WithdrawView alloc] initWithFrame:self.view.bounds];
    self.view = self.wv;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"提现";
    [self createNum];
    [self.payBtn addTarget:self action:@selector(payBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    //查询银行卡号,并显示后4位
    [self getReceiptCard];
    
    self.wv.ableWithdrawLab.text = [NSString stringWithFormat:@"%@%@",@"账户可提现余额￥",self.ableWithdrawStr];
    
}

-(void)getReceiptCard
{
    NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/user/userInfoE0100"];
    [[ETONEHttpClient sharedInstance] doHTTPSPOST:url Parameters:nil HttpBody:nil SuccessHandler:^(id responseObject) {
        
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
            [self dealGetReceiptWith:responseObject];
        }
        
    } FailedHandler:^(NSError *error) {
        
    }];
}

-(void)dealGetReceiptWith:(id)responseObject
{
    GetReceiptCardResponse *getReceiptResponse = [GetReceiptCardResponse mj_objectWithKeyValues:responseObject];
    NSString *bankNameStr = getReceiptResponse.response.openBankName;
    NSString *banCardNumStr = [AppTools changeCardNum:getReceiptResponse.response.accountNo];
    NSString *str = [NSString stringWithFormat:@"%@(尾号%@)",bankNameStr,banCardNumStr];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, str.length)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:51.0f/255.0f green:51.0f/255.0f blue:51.0f/255.0f alpha:1.0f] range:NSMakeRange(0, bankNameStr.length)];
    
    
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:153.0f/255.0f green:153.0f/255.0f blue:153.0f/255.0f alpha:1.0f] range:NSMakeRange(bankNameStr.length, 8)];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.wv.tailNumberLab.attributedText = attributedString;
    });
    
    
}


-(void)payBtnAction
{
    NSLog(@"点击确认收款");
    NSLog(@"金额为:%.2f",[self.wv.visableTf.text floatValue]);
    
    if (self.wv.visableTf.text.length == 0) {
        return;
    }
    
    
    //如果提现余额>可提现余额  提示错误信息
    if ([self.ableWithdrawStr floatValue] < [self.wv.visableTf.text floatValue]) {
        [self showFailedResultTips:[NSString stringWithFormat:@"%@%@%@",@"提现余额不能大于￥",self.ableWithdrawStr,@"元"]animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        return;
    }
    
    
    NSDictionary *dic = @{@"transAmount":self.wv.visableTf.text}.mutableCopy;
    NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/book/withdrawCashT1E0500"];
    [[ETONEHttpClient sharedInstance] doHTTPSPOST:url Parameters:dic HttpBody:nil SuccessHandler:^(id responseObject) {
        
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
        }
        
    } FailedHandler:^(NSError *error) {
        
    }];
    
}
-(void)dealWithdraw:(id)responseObject
{
    [self showSuccessResultTips:@"提现成功" animated:YES forSeconds:SUCCESS_SHOW_TIME_DEF completionBlock:^{
        [self.navigationController popToRootViewControllerAnimated:YES];
    }];
}

-(void)createNum
{
    self.titleArray = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@".",@"0",@"00",].mutableCopy;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat with = WIDTH / 4.0;
    CGFloat higth = with - 20;
    layout.itemSize = CGSizeMake(with, higth);
    NSLog(@"%f%f",with,higth);
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, HEIGHT - higth * 4  - ETTopHeight - ETTabBarArcHeight, WIDTH - WIDTH / 4.0, higth * 4) collectionViewLayout:layout];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.wv addSubview:self.collectionView];
    self.collectionView.backgroundColor = [UIColor colorWithRed:238 / 255.0 green:238 / 255.0 blue:240 / 255.0 alpha:1];
    [self.collectionView registerClass:[HNineCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    
    UIView *horizontalLineView1 = [[UIView alloc] init];
    horizontalLineView1.backgroundColor = [UIColor colorWithRed:225 / 255.0 green:225 / 255.0 blue:225 / 255.0 alpha:1];
    horizontalLineView1.frame = CGRectMake(0, HEIGHT - higth * 4 -  ETTopHeight - ETTabBarArcHeight, WIDTH, 1);
    [self.view addSubview:horizontalLineView1];
    
    
    
    UIView *horizontalLineView2 = [[UIView alloc] init];
    horizontalLineView2.backgroundColor = [UIColor colorWithRed:225 / 255.0 green:225 / 255.0 blue:225 / 255.0 alpha:1];
    horizontalLineView2.frame = CGRectMake(0, HEIGHT - higth * 4 -  ETTopHeight - ETTabBarArcHeight + higth, WIDTH - WIDTH / 4.0, 1);
    [self.view addSubview:horizontalLineView2];
    
    UIView *horizontalLineView3 = [[UIView alloc] init];
    horizontalLineView3.backgroundColor = [UIColor colorWithRed:225 / 255.0 green:225 / 255.0 blue:225 / 255.0 alpha:1];
    horizontalLineView3.frame = CGRectMake(0, HEIGHT - higth * 4 -  ETTopHeight - ETTabBarArcHeight + higth * 2, WIDTH - WIDTH / 4.0, 1);
    [self.view addSubview:horizontalLineView3];
    
    
    UIView *horizontalLineView4 = [[UIView alloc] init];
    horizontalLineView4.backgroundColor = [UIColor colorWithRed:225 / 255.0 green:225 / 255.0 blue:225 / 255.0 alpha:1];
    horizontalLineView4.frame = CGRectMake(0, HEIGHT - higth * 4 -  ETTopHeight - ETTabBarArcHeight + higth * 3, WIDTH - WIDTH / 4.0, 1);
    [self.view addSubview:horizontalLineView4];
    
    //如果是刘海屏手机最底部增加一条线
    UIView *horizontalLineView5 = [[UIView alloc] init];
    horizontalLineView5.backgroundColor = [UIColor colorWithRed:225 / 255.0 green:225 / 255.0 blue:225 / 255.0 alpha:1];
    horizontalLineView5.frame = CGRectMake(0, HEIGHT - higth * 4 -  ETTopHeight - ETTabBarArcHeight + higth * 4 - 1, WIDTH - WIDTH / 4.0, 1);
    [self.view addSubview:horizontalLineView5];
    
    
    
    UIView *verticalLineView1 = [[UIView alloc] init];
    verticalLineView1.backgroundColor = [UIColor colorWithRed:225 / 255.0 green:225 / 255.0 blue:225 / 255.0 alpha:1];
    verticalLineView1.frame = CGRectMake(WIDTH / 4.0, HEIGHT - higth * 4 -  ETTopHeight - ETTabBarArcHeight,  1, higth *4);
    [self.view addSubview:verticalLineView1];
    
    
    UIView *verticalLineView2 = [[UIView alloc] init];
    verticalLineView2.backgroundColor = [UIColor colorWithRed:225 / 255.0 green:225 / 255.0 blue:225 / 255.0 alpha:1];
    verticalLineView2.frame = CGRectMake(WIDTH / 4.0 * 2, HEIGHT - higth * 4 -  ETTopHeight - ETTabBarArcHeight,  1, higth * 4);
    [self.view addSubview:verticalLineView2];
    
    
    UIView *verticalLineView3 = [[UIView alloc] init];
    verticalLineView3.backgroundColor = [UIColor colorWithRed:225 / 255.0 green:225 / 255.0 blue:225 / 255.0 alpha:1];
    verticalLineView3.frame = CGRectMake(WIDTH / 4.0 * 3, HEIGHT - higth * 4 -  ETTopHeight - ETTabBarArcHeight,  1, higth);
    [self.view addSubview:verticalLineView3];
    
    self.delBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [self.delBtn setImage:[UIImage imageNamed:@"icon_revoke"] forState:(UIControlStateNormal)];
    self.delBtn.frame = CGRectMake(with * 3, HEIGHT - higth * 4 -  ETTopHeight - ETTabBarArcHeight, with, higth);
    [self.view addSubview:self.delBtn];
    
    self.payBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [self.payBtn setTitle:@"确认\n收款" forState:(UIControlStateNormal)];
    [self.payBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    self.payBtn.titleLabel.numberOfLines = 0;
    self.payBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    self.payBtn.backgroundColor = [UIColor colorWithRed:219 / 255.0 green:224 / 255.0 blue:255 / 255.0 alpha:1];
    self.payBtn.frame = CGRectMake(with * 3, HEIGHT - higth * 4 -  ETTopHeight - ETTabBarArcHeight + higth, with, higth * 3);
    [self.view addSubview:self.payBtn];
    
    
    [self.delBtn addTarget:self action:@selector(delBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    //隐藏系统键盘
    self.wv.visableTf.inputView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.wv.visableTf becomeFirstResponder];
    self.wv.visableTf.delegate = self;
    [self.wv.visableTf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.wv.visableTf becomeFirstResponder];
}

-(void)textFieldDidChange :(UITextField *)textField{
    //超过8位变小
    if (textField.text.length >= 8) {
        self.wv.visableTf.font = [UIFont systemFontOfSize:40.0];
    }
    
    if (textField.text.length < 8) {
        self.wv.visableTf.font = [UIFont systemFontOfSize:48.0];
    }
    
    if ([textField.text isEqualToString:@"0"]) {
        self.payBtn.userInteractionEnabled = NO;
        self.payBtn.backgroundColor = [UIColor colorWithRed:219 / 255.0 green:224 / 255.0 blue:255 / 255.0 alpha:1];
        return;
    }
    
    if ([textField.text isEqualToString:@"0."]) {
        self.payBtn.userInteractionEnabled = NO;
        self.payBtn.backgroundColor = [UIColor colorWithRed:219 / 255.0 green:224 / 255.0 blue:255 / 255.0 alpha:1];
        return;
    }
    
    if (textField.text.length > 0) {
        self.payBtn.userInteractionEnabled = YES;
        self.payBtn.backgroundColor = [UIColor colorWithRed:91 / 255.0 green:113 / 255.0 blue:255 / 255.0 alpha:1];
    }else
    {
        self.payBtn.userInteractionEnabled = NO;
        self.payBtn.backgroundColor = [UIColor colorWithRed:219 / 255.0 green:224 / 255.0 blue:255 / 255.0 alpha:1];
    }
}

//只允许输入小数点后2位
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    
    NSMutableString *futureString = [NSMutableString stringWithString:textField.text];
    [futureString insertString:string atIndex:range.location];
    
    NSInteger flag = 0;
    // 这个可以自定义,保留到小数点后两位,后几位都可以
    const NSInteger limited = 2;
    
    for (NSInteger i = futureString.length - 1; i >= 0; i--) {
        
        if ([futureString characterAtIndex:i] == '.') {
            // 如果大于了限制的就提示
            if (flag > limited) {
                
                NSLog(@"只能输入小数点后两位");
                return NO;
            }
            
            break;
        }
        
        flag++;
    }
    
    return YES;
}

-(void)delBtnAction
{
    if ([self.wv.visableTf.text length] == 0) {
        return ;
    }
    [self.wv.visableTf deleteBackward];
}
-(NSString*) removeLastValueFromAmount:(NSString*) amount{
    NSString* originalCentStr = [amount stringByReplacingOccurrencesOfString:@"." withString:@""];
    NSString* newCentStr = [originalCentStr substringToIndex:[originalCentStr length]-1];
    NSString* yuanStr = [self cent2Yuan:newCentStr];
    return yuanStr;
}
-(BOOL)inputRulesWithindepath:(NSIndexPath *)indexPath
{
    //如果输入了"点",再次输入"点"   或者第一位是"点"   禁止输入
    if ([self.wv.visableTf.text containsString:@"."] || self.wv.visableTf.text.length == 0) {
        if (indexPath.row == 9) {
            return NO;
        }
    }
    
    
    if ([self.wv.visableTf.text containsString:@"."]) {
        NSRange range1 = [self.wv.visableTf selectedRange1];
        NSRange range = [self.wv.visableTf.text rangeOfString:@"."];
        if (range1.location <= range.location) {
            //可以添加(获取到光标位置在小数点之前)
        }else
        {
            //如果小数点后面已经有了2位,禁止继续输入
            if ([self.wv.visableTf.text containsString:@"."]) {
                NSRange range = [self.wv.visableTf.text rangeOfString:@"."];
                NSMutableString *string = [NSMutableString stringWithString:self.wv.visableTf.text];
                [string insertString:[NSString stringWithFormat:@"%ld",indexPath.row] atIndex:range.location];
                NSInteger flag;
                if (indexPath.row == 11) {
                    flag = 2;
                }else
                {
                    flag = 1;
                }
                
                const NSInteger limited = 2;
                for (NSInteger i = string.length - 1; i  >= 0; i--) {
                    if ([string characterAtIndex:i] == '.') {
                        if (flag > limited) {
                            NSLog(@"小数点后两位了");
                            return NO;
                        }
                        break;
                    }
                    flag++;
                }
                //这里return Yes
                //        return YES;
                
            }
        }
    }
    
    
    
    //如果第一位是0  后面只能输入"点"
    if ([@"0" isEqualToString:self.wv.visableTf.text]) {
        if (indexPath.row != 9) {
            return NO;
        }
    }
    
    //不能直接输入”00“
    if (self.wv.visableTf.text.length == 0) {
        if (indexPath.row == 11) {
            return NO;
        }
    }
    return YES;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //检测输入是否合法
    BOOL flag = [self inputRulesWithindepath:indexPath];
    if (!flag) {
        return;
    }
    
    if (self.wv.visableTf.text.length >= 10) {
        return;
    }
    
    if(self.wv.visableTf.text.length < 90){
        self.HoriginalAmount = [self.wv.visableTf text];
        self.HnewAccount = nil;
        switch (indexPath.row) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            {
                NSString *lastValueStr = [NSString stringWithFormat:@"%ld",indexPath.row + 1];
                [self.wv.visableTf insertText:lastValueStr];
                break;
            }
            case 9:
            {
                [self.wv.visableTf insertText:@"."];
                break;
            }
            case 10:
            {
                if (self.wv.visableTf.text.length == 0) {
                    return;
                }
                
                [self.wv.visableTf insertText:@"0"];
                break;
            }
            case 11:
            {
                [self.wv.visableTf insertText:@"00"];
                break;
            }
            default:
                break;
        }
    }
}

-(NSString*) addLastValueToAmount:(NSString*) amount LastValue:(NSString*)value{
    NSString* originalCentStr = [amount stringByReplacingOccurrencesOfString:@"." withString:@""];
    NSString* newCentStr = [originalCentStr stringByAppendingString:value];
    NSString* yuanStr = [self cent2Yuan:newCentStr];
    return yuanStr;
}
-(NSString*)cent2Yuan:(NSString*)centStr{
    double cent = [centStr doubleValue];
    double yuan = cent/100;
    NSString*  yuanStr = [NSString stringWithFormat:@"%.2f",yuan];
    return yuanStr;
}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.titleArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HNineCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.titleLab.text = self.titleArray[indexPath.row];
    cell.backgroundColor = [UIColor whiteColor];
    return cell;
}

@end
